#include "malloc.h"	    
#pragma pack(4)
unsigned char membase[MEM_MAX_SIZE];			
#pragma pack()
unsigned short memmapbase[MEM_ALLOC_TABLE_SIZE];			
  
const unsigned int memtblsize=MEM_ALLOC_TABLE_SIZE;		
const unsigned int memblksize=MEM_BLOCK_SIZE;			
const unsigned int memsize=MEM_MAX_SIZE;					


struct _m_mallco_dev mallco_dev=
{
	mem_init,			
	mem_perused,		
	membase,			
	memmapbase,			
	0,  				
};


void mymemcpy(void *des,void *src,unsigned int n)  
{  
    unsigned char *xdes=des;
	unsigned char *xsrc=src; 
    while(n--)*xdes++=*xsrc++;  
}  

void mymemset(void *s,unsigned char c,unsigned int count)  
{  
    unsigned char *xs = s;  
    while(count--)*xs++=c;  
}	   
  
void mem_init(void)  
{  
    mymemset(mallco_dev.memmap, 0,memtblsize*2); 
	mymemset(mallco_dev.membase, 0,memsize);	 
	mallco_dev.memrdy=1;						
}  

unsigned char mem_perused(void)  
{  
    unsigned int used=0;  
    unsigned int i;  
    for(i=0;i<memtblsize;i++)  
    {  
        if(mallco_dev.memmap[i])used++; 
    } 
    return (used*100)/(memtblsize);  
}  

unsigned int mem_malloc(unsigned int size)  
{  
    signed long offset=0;  
    unsigned char nmemb;	 
	unsigned char cmemb=0;
    unsigned int i;  
    if(!mallco_dev.memrdy)mallco_dev.init();	
    if(size==0)return 0XFFFFFFFF;				
    nmemb=size/memblksize;  					
    if(size%memblksize)nmemb++;  
    for(offset=memtblsize-1;offset>=0;offset--)	 
    {     
		if(!mallco_dev.memmap[offset])cmemb++;	
		else cmemb=0;							
		if(cmemb==nmemb)						
		{
            for(i=0;i<nmemb;i++)  				
            {  
                mallco_dev.memmap[offset+i]=nmemb;  
            }  
            return (offset*memblksize);			
		}
    }  
    return 0XFFFFFFFF;
}  
  
unsigned char mem_free(unsigned int offset)  
{  
    int i;  
    if(!mallco_dev.memrdy)
	{
		mallco_dev.init();    
        return 1;  
    }  
    if(offset<memsize)
    {  
        int index=offset/memblksize;		  
        int nmemb=mallco_dev.memmap[index];	
        for(i=0;i<nmemb;i++)  				
        {  
            mallco_dev.memmap[index+i]=0;  
        }
        return 0;  
    }else return 2; 
}  

void myfree(void *ptr)  
{  
	unsigned int offset;  
    if(ptr==NULL)return;
 	offset=(unsigned int)ptr-(unsigned int)mallco_dev.membase;  
    mem_free(offset);	    
}  

void *mymalloc(unsigned int size)  
{  
    unsigned int offset;  									      
	offset=mem_malloc(size);  	   				   
    if(offset==0XFFFFFFFF)return NULL;  
    else return (void*)((unsigned int)mallco_dev.membase+offset);  
}  

void *myrealloc(void *ptr,unsigned int size)  
{  
    unsigned int offset;  
    offset=mem_malloc(size);  
    if(offset==0XFFFFFFFF)return NULL;     
    else  
    {  									   
	    mymemcpy((void*)((unsigned int)mallco_dev.membase+offset),ptr,size);	  
        myfree(ptr);  											  	
        return (void*)((unsigned int)mallco_dev.membase+offset);  			
    }  
}












